﻿using Blm.Utils.Extensions;
using Blm.Utils.Utility;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net;
using System.Net.Security;
using System.Threading.Tasks;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Inner;
using VisionCloud.Service.Ms;
using VisionCloud.Service.Sys;
using VisionCloud.Utility;
using VisionCloud.Utility.Security;

namespace VisionCloud.Service.Fms
{
    /// <summary>
    /// Fms接口服务
    /// </summary>
    public class FmsService
    {
        /// <summary>
        /// 设备服务
        /// </summary>
        public SysDeviceService SysDeviceService { get; set; }

        /// <summary>
        /// 项目服务
        /// </summary>
        public ProjectService ProjectService { get; set; }

        private static string server = ConfigHelper.GetValue<string>("FmsServer");

        static FmsService()
        {
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((s, c, c2, c3) => { return true; });
        }

        /// <summary>
        /// 作者：黄钧航
        /// 获取Fms系统公钥
        /// </summary>
        /// <returns></returns>
        public static async Task<FmsApiResult> GetFmsPublicKey()
        {
            var api = $"{server}/sit/v1/system/getPublicKey";
            FmsApiResult apiResult = new FmsApiResult();
            using (var response = await HttpUtility.GetAsync(api, null, 60))
            {
                if (response == null)
                {
                    Logger.Error($"{api}远程服务器没响应!");
                    apiResult.Message = "YB0050".SLocalize();
                    return apiResult;
                }
                if (response.IsSuccessStatusCode)
                {
                    var responseStr = await response.Content.ReadAsStringAsync();
                    apiResult = JsonConvert.DeserializeObject<FmsApiResult>(responseStr);
                    if (apiResult.Code == 0)
                    {
                        return apiResult;
                    }
                    else
                    {
                        Logger.Warn($"fms code:{responseStr}[{response.StatusCode}]");
                        return apiResult;
                    }
                }
                else
                {
                    var responseStr = await response.Content.ReadAsStringAsync();
                    Logger.Warn($"fms server login failed:{responseStr}[{response.StatusCode}]");
                    apiResult.Message = "StatusCode:" + response.StatusCode;
                    return apiResult;
                }
            }
        }

        /// <summary>
        /// 作者：黄钧航
        /// 授权Fms系统的授权Id
        /// </summary>
        /// <returns></returns>
        public static async Task<FmsApiResult> UserLoginFms()
        {
            FmsApiResult result = await GetFmsPublicKey();
            if (result.Code != 0)
            {
                return result;
            }

            if (result.Data == null || string.IsNullOrWhiteSpace(result.Data.PublicKey))
            {
                throw new OperationException("YB0049".SLocalize());
            }

            var api = $"{server}/sit/v1/system/userLogin";
            var user = new { username = "measure", password = "Fms123@." };   // 默认登录用户名
            RSACryptoService rsaHelper = new RSACryptoService(string.Empty, result.Data.PublicKey);
            string encryptAccountInfo = rsaHelper.Encrypt(user.ToJsonStr());  // 加密用户对象json字符串

            var data = new { uuid = result.Data.Uuid, rsaMessage = encryptAccountInfo };
            var apiResult = new FmsApiResult();
            using (var response = await HttpUtility.PostAsync(api, JsonConvert.SerializeObject(data), 60))
            {
                if (response == null)
                {
                    Logger.Error($"{api}远程服务器没响应!");
                    apiResult.Message = "YB0050".SLocalize();
                    return apiResult;
                }
                if (response.IsSuccessStatusCode)
                {
                    var responseStr = await response.Content.ReadAsStringAsync();
                    apiResult = JsonConvert.DeserializeObject<FmsApiResult>(responseStr);
                    if (apiResult.Code == 0)
                    {
                        return apiResult;
                    }
                    else
                    {
                        Logger.Warn($"fms code:{responseStr}[{response.StatusCode}]");
                        return apiResult;
                    }
                }
                else
                {
                    var responseStr = await response.Content.ReadAsStringAsync();
                    Logger.Warn($"fms server login failed:{responseStr}[{response.StatusCode}]");
                    apiResult.Message = "StatusCode:" + response.StatusCode;
                    return apiResult;
                }
            }
        }

        /// <summary>
        /// 作者：黄钧航
        /// 将设备信息写入Fms系统
        /// </summary>
        /// <returns></returns>
        public async Task<string> RegisterForApp()
        {
            string msg = string.Empty;
            FmsApiResult result = await UserLoginFms();  // 登录授权
            if (result.Code != 0)
            {
                return result.Message;
            }

            var devices = await SysDeviceService.GetAllActivedDevices();
            if (devices == null || devices.Count == 0)
            {
                return "YB0051".SLocalize();
            }

            var api = $"{server}/sit/v1/robot/measure/register";
            var header = new Dictionary<string, string> { { "token", result.Data.Token } };
            foreach (var device in devices)
            {
                var model = new { DeviceCode = device.DeviceNumber, RobotType = "Z008", Version = "1.0" };
                using (var response = await HttpUtility.PostAsync(api, JsonConvert.SerializeObject(model), 60, header))
                {
                    if (response == null)
                    {
                        msg = $"{api}{"YB0058".SLocalize()}";
                        Logger.Error(msg);
                        continue;
                    }
                    if (response.IsSuccessStatusCode)
                    {
                        var responseStr = await response.Content.ReadAsStringAsync();
                        var apiResult = JsonConvert.DeserializeObject<FmsApiResult>(responseStr);
                        if (apiResult.Code == 0)
                        {
                            msg = string.Empty;
                        }
                        else
                        {
                            msg = $"fms code: {responseStr}[{response.StatusCode}]";
                            Logger.Error(msg);
                            //return msg;
                        }
                    }
                    else
                    {
                        var responseStr = await response.Content.ReadAsStringAsync();
                        msg = $"fms code: {responseStr}[{response.StatusCode}]";
                        Logger.Error(msg);
                        //return msg;
                    }
                }
            }

            return msg;
        }

        /// <summary>
        /// 作者：黄钧航
        /// 将项目信息写入Fms系统
        /// </summary>
        /// <returns></returns>
        public async Task<string> BatchUpdateProjectInfo()
        {
            string msg = string.Empty;
            FmsApiResult result = await UserLoginFms();  // 登录授权
            if (result.Code != 0)
            {
                return result.Message;
            }

            var projects = await ProjectService.GetAllProjects();
            if (projects == null || projects.Count == 0)
            {
                return "YB0052".SLocalize();
            }

            var api = $"{server}/sit/v1/robot/measure/batchUpdateProjectInfo";
            var header = new Dictionary<string, string> { { "token", result.Data.Token } };
            List<object> models = new List<object>();
            foreach (var project in projects)
            {
                models.Add(new { DeviceCode = project.DeviceNumber, ProjectName = project.ProjectName });   // 构建项目列表数据
            }

            var model = new { UpdateList = models };
            using (var response = await HttpUtility.PostAsync(api, JsonConvert.SerializeObject(model), 60, header))
            {
                if (response == null)
                {
                    msg = $"{api}{"YB0058".SLocalize()}";
                    return msg;
                }
                if (response.IsSuccessStatusCode)
                {
                    var responseStr = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonConvert.DeserializeObject<FmsApiResult>(responseStr);
                    if (apiResult.Code == 0)
                    {
                        msg = string.Empty;
                    }
                    else
                    {
                        msg = $"fms code: {responseStr}[{response.StatusCode}]";
                        return msg;
                    }
                }
                else
                {
                    var responseStr = await response.Content.ReadAsStringAsync();
                    msg = $"fms code: {responseStr}[{response.StatusCode}]";
                    return msg;
                }
            }

            return msg;
        }
    }
}